package com.tangdi.production.mpaychl.service.impl.gpayotc;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.tangdi.production.mpaychl.base.service.BaseTranService;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.TranException;
import com.tangdi.production.mpbase.util.MoneyUtils;
import com.tangdi.production.mpbase.util.ObjectUtil;
import com.tangdi.production.tdbase.util.MD5Util;

@Service("Gpay_Service")
public class GpayServiceImpl implements BaseTranService {
	private static final Logger logger = LoggerFactory.getLogger(GpayServiceImpl.class);

	private static final String pay_url = "http://www.gpayotc.com/client/tracnce";

	private static final String pay_notify_url = "http://ce.imbitpay.com:8083/mpcctp/gpay/notify-url.json";

	private static final String shop_no = "198";

	public static final String md5_key = "ONbRvrFT4G";

	@Override
	public Map<String, Object> execute(Map<String, Object> params) throws TranException {
		try {
			String orderNo = "" + params.get("prdordno");
			String customerId = params.get("goodsName") == null ? "" : "" + params.get("goodsName");
			String orderCurrency = "CNY";
			String payAmt = ObjectUtil.getString(params.get("payAmt"));
			logger.info("支付金额[{}分]", payAmt);
			payAmt = MoneyUtils.toStrYuan(payAmt);
			logger.info("支付金额转换为元[{}]", payAmt);
			String orderAmount = payAmt;
			String receiveUrl = pay_notify_url;
			String pickupUrl = "" + params.get("frontUrl");
			String signType = "MD5";
			
			String signStr = pickupUrl + receiveUrl + signType + orderNo + orderAmount + orderCurrency
					+ customerId + md5_key;
			
			String sign = MD5Util.encode(signStr.getBytes());
			
			StringBuilder sbd = new StringBuilder(pay_url);
			sbd.append("?shopNo=").append(shop_no);
			sbd.append("&orderNo=").append(orderNo);
			sbd.append("&customerId=").append(customerId);
			sbd.append("&orderCurrency=").append(orderCurrency);
			sbd.append("&orderAmount=").append(orderAmount);
			sbd.append("&receiveUrl=").append(receiveUrl);
			sbd.append("&pickupUrl=").append(pickupUrl);
			sbd.append("&signType=").append(signType);
			sbd.append("&sign=").append(sign);
			
			logger.info(sbd.toString());
			
			Map<String,Object> backMap = new HashMap<>();
			backMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
			backMap.put("contentType", MsgCT.DATA_TYPE_STRING);
			backMap.put("busContent", sbd.toString());
			return backMap;
		} catch (Exception e){
			logger.error("处理gpay支付通道异常:{}", e.getMessage(), e);
			Map<String,Object> backMap = new HashMap<>();
			backMap.put("ordStatus", MsgCT.ORDSTATUS_FAIL);
			backMap.put("msg", "渠道gpay调用异常:" + e.getMessage());
			return backMap;
		}
	}
	
}
